package com.smartcar.service;

import com.smartcar.tcp.TCPClientManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * 心跳包服务
 * 对应原HarmonyOS的TCPClientSendUtils
 */
@Slf4j
@Service
public class HeartbeatService {

    private final TCPClientManager tcpClientManager;
    private int heartbeatCount = 0;

    public HeartbeatService(TCPClientManager tcpClientManager) {
        this.tcpClientManager = tcpClientManager;
    }

    /**
     * 发送心跳包
     * 每5秒发送一次
     */
    @Scheduled(fixedRate = 5000)
    public void sendHeartbeat() {
        if (tcpClientManager.isConnected()) {
            heartbeatCount++;
            String heartbeatMessage = "heartbeat_" + (heartbeatCount % 8);
            
            tcpClientManager.sendMessage(heartbeatMessage)
                    .thenAccept(success -> {
                        if (success) {
                            log.debug("心跳包发送成功: {}", heartbeatMessage);
                        } else {
                            log.warn("心跳包发送失败: {}", heartbeatMessage);
                        }
                    });
        } else {
            log.debug("TCP未连接，跳过心跳包发送");
        }
    }

    /**
     * 获取心跳计数
     */
    public int getHeartbeatCount() {
        return heartbeatCount % 8;
    }
} 